package com.ifgi.sitcom.campusmapperNDrawer.dialogs;



import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.osmdroid.views.overlay.OverlayItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.gamificationlibrary.model.*;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.PersonBuffer;
import com.ifgi.sitcom.campusmapperNDrawer.R;
import com.ifgi.sitcom.campusmapperNDrawer.activities.MainActivity;
import com.ifgi.sitcom.campusmapperNDrawer.activities.SignInActivity;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.OwnershipController;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.PlayerController;
import com.ifgi.sitcom.campusmapperNDrawer.fragments.ChooseLocationFragment;
import com.ifgi.sitcom.campusmapperNDrawer.fragments.MapFragment;
import com.ifgi.sitcom.campusmapperNDrawer.gamedata.PlayerAdapter;
import com.ifgi.sitcom.campusmapperNDrawer.gamedata.SerialBitmap;
import com.ifgi.sitcom.campusmapperNDrawer.indoordata.FloorPlan;
import com.ifgi.sitcom.campusmapperNDrawer.io.RDFReader;
import com.ifgi.sitcom.campusmapperNDrawer.outdoordata.Building;

/*
 * 
 *  dialog  shown when room was created/ edited
 */
public class MenuListDialog extends SherlockDialogFragment implements PlusClient.OnPeopleLoadedListener {

	private ArrayList<Ownership<FloorPlan>> floorOwners;
	private FragmentActivity activity;
	private ProgressDialog mProgressDialog;

	private OwnerDialog dialog;
	private Ownership<Building> buildingOwnership;
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) 
	{
		activity=getActivity();
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		final Bundle bundle=getArguments();
		String[] list=null;
		 if(bundle.get("put_lookOwners").equals("yes"))
		 {
			list=new String[2];
			list[0]="Collect data";
			list[1]="Look owners";
		 }
		 else
		 {
			 list=new String[1];
			 list[0]="Collect data";
		 }
	
		 android.support.v4.app.FragmentManager fm = activity.getSupportFragmentManager();
		 MapFragment fragment = (MapFragment) fm.findFragmentByTag("mapFragment");
		 buildingOwnership=fragment.getOwnershipFromBName(bundle.getString("item_name"));
		 
		 builder.setTitle(Html.fromHtml("<b>"+Building.trunkName(buildingOwnership.getT().getBuildingName(),28)+
				"</b> <br>Lat "+new DecimalFormat("#.######").format(buildingOwnership.getT().getCenter().getLatitude())+
				", Long "+new DecimalFormat("#.######").format(buildingOwnership.getT().getCenter().getLongitude())+"</br>"))
	           .setItems(list, new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int which) {
	               // The 'which' argument contains the index position
	               // of the selected item
	            	   if(bundle.getString("put_lookOwners").equals("yes"))
	       			   {
	            	   if(which==0)
	            	   {
	            		    startCollectData(bundle);
	            	   }
	            	   else
	            	   {
	            		   mProgressDialog = ProgressDialog.show(getActivity(),
	       						"Please, wait...",
	       						"Loading owners",
	       						true);
	            		             		   
	            		   new LoadOwnershipFloorFromLODUM().execute(bundle.getString("item_name"));
	            	   }
	       			   }
	            	   else
	            	   {
	            		   startCollectData(bundle);
	            	   }
	           
	               }
	           
	    });
	    return builder.create();
	}
	
	
private class LoadOwnershipFloorFromLODUM extends AsyncTask<String, Void, ArrayList<Ownership<FloorPlan>>> {
		
	
	

		@Override
		protected ArrayList<Ownership<FloorPlan>> doInBackground(String... params) 
		{
			  
			String name = params[0];
			floorOwners=OwnershipController.getInstance().getFloorOwnerships(name);
			
		    ArrayList<String> n=new ArrayList<String>();
			
			
			dialog=new OwnerDialog();
			n.add(((PlayerAdapter) buildingOwnership.getP()).getIDPlus());
			
			for(int i=0;i<floorOwners.size();i++)
			{
		
				n.add(((PlayerAdapter) floorOwners.get(i).getP()).getIDPlus());
				Log.v("numberFloor",String.valueOf(floorOwners.get(i).getT().getFloorNumber()));
			}
				Log.v("size", String.valueOf(floorOwners.size()));
			
			PlusClient p=((MainActivity) activity).getmPlusClient();
			p.loadPeople(MenuListDialog.this, n);
			
			
			return floorOwners;
		}
		
		@Override
		protected void onPostExecute(ArrayList<Ownership<FloorPlan>> result) {
			// custom dialog
	
		}
		
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected void onProgressUpdate(Void... values) {
		}
	
	}

@Override
public void onPeopleLoaded(ConnectionResult status, PersonBuffer personBuffer,
        String nextPageToken) {
	// TODO Auto-generated method stub
	

	if (status.getErrorCode() == ConnectionResult.SUCCESS) {
        try {
        	Log.v("Count",String.valueOf(personBuffer.getCount()));
            for(int i=0;i<personBuffer.getCount();i++) {
                Log.d("Displayname", "Display Name: " + personBuffer.get(i).getDisplayName());
                
                Log.v("ii", String.valueOf(i));
            	String urldisplay = personBuffer.get(i).getImage().getUrl();
            	new DownloadImageTask().execute(String.valueOf(i),urldisplay);
                
            }
        } finally {
            personBuffer.close();
        }
    } else {
        Log.e("Error", "Error listing people: " + status.getErrorCode());
    }
	
	
    
	
  
}
private boolean put_iconBuilding=false;
private class DownloadImageTask extends AsyncTask<String, Void, SerialBitmap> {
	  
	private int pos;
	

	protected SerialBitmap doInBackground(String... urls) {
		 pos=Integer.parseInt(urls[0]);
		 Log.v("Integer.parseInt(urls[0])",urls[0]);
	            String urldisplay=urls[1].substring(0, urls[1].length()-2)+"100";
	            Log.v("URL", urldisplay);
	            SerialBitmap mIcon11 = null;
	            try {
	              InputStream in = new java.net.URL(urldisplay).openStream();
	              mIcon11 = new SerialBitmap(in);
	            } catch (Exception e) {
	                Log.e("Error", e.getMessage());
	                e.printStackTrace();
	            }
	           
	           if(put_iconBuilding)
	           {
	        		           
	            ((PlayerAdapter) floorOwners.get(pos-1).getP()).setPicture(mIcon11);
	         
	           }
	           else
	        	   {
	        	   Log.v("pos", String.valueOf(pos));Log.v("bOwn", "bOwn");((PlayerAdapter) buildingOwnership.getP()).setPicture(mIcon11);put_iconBuilding=true;}
	           
	  	      return null;
		  
	  }

	  protected void onPostExecute(SerialBitmap result) {
		
		if(pos==floorOwners.size())
			{
			mProgressDialog.dismiss();
			Log.v("sizeFloors",String.valueOf(floorOwners.size()));
			dialog.setFields(buildingOwnership,floorOwners);
		    dialog.show(activity.getSupportFragmentManager(), "owner_information");
		    }
		 
	  }
	}




	private void startCollectData(Bundle bundle)
	{
		ChooseLocationFragment fragment = new ChooseLocationFragment();
		Bundle b=new Bundle();
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_NAME, bundle.getString("item_name"));
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_URI, bundle.getString("item_URI"));
		fragment.setArguments(b);
		
		android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
   	    ft.addToBackStack(null);
    	ft.commit();
		
	}


	
	

}
